package com.cdut.controller;

import com.cdut.pojo.Good;
import com.cdut.pojo.User;
import com.cdut.service.GoodService;
import com.cdut.service.UserService;
import com.cdut.util.JsonResponce;
import com.cdut.util.VerificationCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Objects;

/**
 * author: xinmu
 * date: 2022/4/22
 * time: 20:34
 */

@Api("邮件发送控制器")
@Controller
@RequestMapping("/mail")
@Slf4j
public class MailController {

    Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    Environment environment;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    UserService userService;

    @Autowired
    GoodService goodService;

    @ApiOperation("通过商品id发邮件")
    @GetMapping("/send-by-id")
    //@ResponseBody
    //@Async
    public String sendMailByGoodId(int gid, Model model) throws InterruptedException {

        JsonResponce<Good> goodJsonResponce = goodService.queryGoodById(gid);
        Good good = goodJsonResponce.getData();
        int uid = good.getUid();
        logger.info("商品的发布者的id"+uid);
        JsonResponce<User> userJsonResponce = userService.queryUserById(uid);
        User user = userJsonResponce.getData();
        System.err.println(user);

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser==null){
            session.setAttribute("mailMsg","未登录,操作失败");
            return "redirect:login";
        }else{
            try{
                //创建简单邮件消息
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(Objects.requireNonNull(environment.getProperty("spring.mail.username")));
                message.setTo(user.getMail());
                message.setSubject("👀有人看中了您的发布✨🎉✨");
                message.setText("用户:"+"["+loginUser.getUsername()+"]"+"可能看上了你发布的商品"+'['+good.getGname()+"]"+",你可以尝试联系他,他的邮箱为"+'\n'+loginUser.getMail());
                message.setSentDate(new Date());
                mailSender.send(message);
                logger.info("发送成功=>"+user);
                model.addAttribute("mailMsg","发送成功");

            }catch (MailException e){
                logger.error("邮件发送失败");
                model.addAttribute("mailMsg","发送失败");
            }
        }

        return "redirect:../home";
    }

    @ApiOperation("发送验证码")
    @GetMapping("/send-code")
    @ResponseBody
    public String sendVerificationCode(String mail,String username){

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        int verificationCode = VerificationCode.getVerificationCode();

        JsonResponce<User> userJsonResponce1 = userService.queryUserByName(username);
        JsonResponce<User> userJsonResponce2 = userService.UserSerchBymail(mail);

        //如果邮箱和用户名都不重复
        if (userJsonResponce1.getData()==null&&userJsonResponce2.getData()==null){

            try {
                //验证码放到session中注册的时候取
                session.setAttribute("vcode",verificationCode);

                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(Objects.requireNonNull(environment.getProperty("spring.mail.username")));
                message.setTo(mail);
                message.setSubject("验证码");
                message.setText("您的验证码为:"+verificationCode);
                mailSender.send(message);
                session.setAttribute("regName",username);
                session.setAttribute("regMail",mail);
                logger.info("[mail]:验证码发送成功");
                return "成功";

            }catch (Exception e){
                logger.error("[mail]:验证码发送失败");
                return "错误";
            }

        }
        System.err.println("[mail]"+"用户名或邮箱重复");
        return "错误";
    }
}
